<template>
  <div class="agent-selector">
    <!-- 智能体选择弹窗 -->
    <div 
      v-if="showSelector" 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in"
    >
      <div 
        class="p-6 rounded-xl shadow-xl max-w-xl w-full mx-4 border animate-scale-in overflow-hidden relative"
        :class="isDarkMode ? 'bg-gray-900 border-gray-700' : 'bg-white border-gray-200'"
      >
        <!-- 加载状态指示器 -->
        <div 
          v-if="isLoading" 
          class="absolute inset-0 bg-black bg-opacity-20 flex items-center justify-center z-50 animate-fade-in backdrop-blur-sm"
        >
          <div class="bg-white/10 backdrop-blur-md p-4 rounded-xl shadow-lg flex items-center space-x-3">
            <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span class="text-white text-sm">处理中...</span>
          </div>
        </div>
        
        <!-- 弹窗标题和关闭按钮 -->
        <div class="flex items-center justify-between mb-5">
          <h3 
            class="text-xl font-bold bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent animate-gradient-x"
          >
            选择智能体
          </h3>
          <button 
            @click="closeSelector"
            class="p-2 rounded-full transition-all duration-300 transform hover:scale-110 hover:rotate-90"
            :class="isDarkMode ? 'hover:bg-gray-800 text-gray-400' : 'hover:bg-gray-100 text-gray-600'"
          >
            <font-awesome-icon icon="times" />
          </button>
        </div>
        
        <!-- 搜索框 -->
        <div class="relative mb-5">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索智能体..."
            class="w-full px-4 py-3 pl-10 rounded-lg transition-all duration-300 outline-none border"
            :class="isDarkMode 
              ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
              : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
          />
          <font-awesome-icon 
            icon="search" 
            class="absolute left-3.5 top-1/2 transform -translate-y-1/2 transition-colors duration-300"
            :class="isDarkMode ? 'text-gray-500' : 'text-gray-400'"
          />
        </div>
        
        <!-- 类别标签 -->
        <div class="flex items-center space-x-2 mb-4 overflow-x-auto pb-2 scrollbar-thin">
          <button
            v-for="category in categories"
            :key="category.id"
            @click="selectCategory(category.id)"
            class="px-3 py-1.5 rounded-full text-sm whitespace-nowrap transition-all duration-300 transform hover:scale-105 flex-shrink-0"
            :class="[
              selectedCategory === category.id 
                ? 'bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white shadow-md' 
                : (isDarkMode 
                    ? 'bg-gray-800 text-gray-300 hover:bg-gray-700' 
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200')
            ]"
          >
            <font-awesome-icon 
              :icon="category.icon" 
              class="mr-1.5"
              :class="category.color" 
            />
            {{ category.name }}
            <!-- 为"我的收藏"添加额外的视觉提示 -->
            <span 
              v-if="category.id === 'favorites'" 
              class="ml-1 inline-block w-2 h-2 rounded-full bg-yellow-400 animate-pulse-slow"
            ></span>
          </button>
        </div>
        
        <!-- 智能体列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[calc(100vh-280px)] overflow-y-auto pr-1 scrollbar-thin">
          <div 
            v-for="(agent, index) in filteredAgents" 
            :key="agent.id"
            @click="selectAgent(agent)"
            class="group flex flex-col p-4 rounded-xl border transition-all duration-500 cursor-pointer transform hover:scale-[1.02] active:scale-[0.98] relative overflow-hidden stagger-item"
            :class="[
              selectedAgentId === agent.id 
                ? (isDarkMode 
                    ? 'border-[#8153ff] bg-gradient-to-r from-[#8153ff]/20 to-[#93dc24]/20' 
                    : 'border-[#8153ff] bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10') 
                : (isDarkMode 
                    ? 'border-gray-700 bg-gray-800/50 hover:bg-gray-800' 
                    : 'border-gray-200 bg-gray-50/50 hover:bg-gray-100')
            ]"
            :style="`--stagger-delay: ${index * 50}ms`"
          >
            <!-- 选中指示器 -->
            <div 
              v-if="selectedAgentId === agent.id" 
              class="absolute top-2 right-29 w-6 h-6 bg-gradient-to-r from-[#8153ff] to-[#93dc24] rounded-full flex items-center justify-center shadow-lg animate-scale-in"
            >
              <font-awesome-icon icon="check" class="text-white text-xs" />
            </div>
            
            <!-- 收藏按钮（视觉增强版） -->
            <button
              @click.stop="toggleFavorite(agent)"
              type="button"
              class="absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center z-20 transition-all duration-300 shadow-sm hover:shadow-md"
              :style="{
                backgroundColor: agent.isFavorite ? '#facc15' : '#6b7280',
                transition: 'all 0.3s ease'
              }"
            >
              <font-awesome-icon 
                icon="star" 
                class="text-white text-sm"
              />
            </button>
            
            <!-- 编辑按钮（仅对自定义智能体显示） -->
            <div
              v-if="agent.isCustom"
              @click.stop="editCustomAgent(agent)"
              class="absolute top-2 right-11 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center shadow-md transform scale-0 opacity-0 transition-all duration-300 group-hover:scale-100 group-hover:opacity-100 hover:bg-blue-600 hover:shadow-lg z-20"
              title="编辑智能体"
            >
              <font-awesome-icon icon="edit" class="text-white text-xs" />
            </div>
            
            <!-- 删除按钮（仅对自定义智能体显示） -->
            <div
              v-if="agent.isCustom"
              @click.stop="deleteCustomAgent(agent.id)"
              class="absolute top-2 right-20 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center shadow-md transform scale-0 opacity-0 transition-all duration-300 group-hover:scale-100 group-hover:opacity-100 hover:bg-red-600 hover:shadow-lg z-20"
              title="删除智能体"
            >
              <font-awesome-icon icon="trash" class="text-white text-xs" />
            </div>
            
            <!-- 智能体图标 -->
            <div 
              class="w-12 h-12 rounded-lg flex items-center justify-center mb-3 shadow-md transition-all duration-500 group-hover:shadow-lg"
              :class="agent.color || 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]'"
            >
              <font-awesome-icon :icon="agent.icon" class="text-white text-xl" />
            </div>
            
            <!-- 智能体信息 -->
            <h4 
              class="text-base font-medium mb-1 transition-colors duration-300" 
              :class="isDarkMode ? 'text-white' : 'text-gray-800'"
            >
              {{ agent.name }}
            </h4>
            
            <p 
              class="text-xs line-clamp-2 transition-colors duration-300" 
              :class="isDarkMode ? 'text-gray-400' : 'text-gray-600'"
            >
              {{ agent.description }}
            </p>
            
            <!-- 智能体标签 -->
            <div class="flex mt-2 flex-wrap gap-1">
              <span 
                v-for="tag in agent.tags" 
                :key="tag"
                class="text-xs px-2 py-0.5 rounded-full transition-colors duration-300"
                :class="isDarkMode ? 'bg-gray-700 text-gray-300' : 'bg-gray-200 text-gray-700'"
              >
                {{ tag }}
              </span>
            </div>
          </div>
          
          <!-- 创建自定义智能体 -->
          <div
            @click="openCustomAgentForm"
            class="group flex flex-col items-center justify-center p-4 rounded-xl border-dashed border-2 transition-all duration-500 cursor-pointer hover:scale-[1.02] active:scale-[0.98] h-full min-h-[120px]"
            :class="isDarkMode ? 'border-gray-700 hover:border-[#8153ff] text-gray-400' : 'border-gray-300 hover:border-[#8153ff] text-gray-500'"
          >
            <div class="w-12 h-12 rounded-full flex items-center justify-center mb-2 transition-all duration-500 group-hover:scale-110">
              <font-awesome-icon icon="plus" :class="isDarkMode ? 'text-gray-400 group-hover:text-[#8153ff]' : 'text-gray-500 group-hover:text-[#8153ff]'" />
            </div>
            <p class="text-sm font-medium transition-colors duration-300 group-hover:text-[#8153ff]">创建自定义智能体</p>
          </div>
        </div>
        
        <!-- 底部操作按钮 -->
        <div class="flex justify-end mt-5 pt-4 border-t" :class="isDarkMode ? 'border-gray-800' : 'border-gray-200'">
          <button
            @click="confirmSelection"
            class="px-4 py-2 rounded-lg text-white font-medium transition-all duration-500 btn-bounce bg-gradient-to-r from-[#8153ff] to-[#93dc24] hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-none flex items-center space-x-2"
            :disabled="!selectedAgentId || isLoading"
          >
            <span v-if="isLoading" class="w-5 h-5">
              <svg class="animate-spin w-full h-full text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </span>
            <span>{{ isLoading ? '处理中...' : '开始对话' }}</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 自定义智能体表单 -->
    <div 
      v-if="showCustomForm" 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in"
    >
      <div 
        class="p-6 rounded-xl shadow-xl max-w-xl w-full mx-4 border animate-scale-in"
        :class="isDarkMode ? 'bg-gray-900 border-gray-700' : 'bg-white border-gray-200'"
      >
        <div class="flex items-center justify-between mb-5">
          <h3 
            class="text-xl font-bold bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent animate-gradient-x"
          >
            创建自定义智能体
          </h3>
          <button 
            @click="showCustomForm = false"
            class="p-2 rounded-full transition-all duration-300 transform hover:scale-110 hover:rotate-90"
            :class="isDarkMode ? 'hover:bg-gray-800 text-gray-400' : 'hover:bg-gray-100 text-gray-600'"
          >
            <font-awesome-icon icon="times" />
          </button>
        </div>
        
        <!-- 表单 -->
        <form @submit.prevent="saveCustomAgent" class="space-y-4">
          <!-- 名称 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              智能体名称
            </label>
            <input
              v-model="customAgent.name"
              type="text"
              required
              placeholder="输入名称"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            />
          </div>
          
          <!-- 描述 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              描述
            </label>
            <textarea
              v-model="customAgent.description"
              rows="3"
              placeholder="输入智能体描述"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border resize-none"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            ></textarea>
          </div>
          
          <!-- 预设提示语 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              预设提示语
            </label>
            <textarea
              v-model="customAgent.systemPrompt"
              rows="5"
              placeholder="输入预设提示语，告诉AI应该扮演什么角色"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border resize-none"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            ></textarea>
          </div>
          
          <!-- 标签 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              标签（用逗号分隔）
            </label>
            <input
              v-model="customAgent.tagsInput"
              type="text"
              placeholder="例: 编程, 助手, 创意"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            />
          </div>
          
          <!-- 底部按钮 -->
          <div class="flex justify-end pt-4 border-t" :class="isDarkMode ? 'border-gray-800' : 'border-gray-200'">
            <button
              type="submit"
              class="px-4 py-2 rounded-lg text-white font-medium transition-all duration-500 btn-bounce bg-gradient-to-r from-[#8153ff] to-[#93dc24] hover:shadow-lg disabled:opacity-70 disabled:cursor-not-allowed flex items-center space-x-2"
              :disabled="isLoading"
            >
              <span v-if="isLoading" class="w-5 h-5">
                <svg class="animate-spin w-full h-full text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              </span>
              <span>{{ isLoading ? '保存中...' : '保存智能体' }}</span>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑智能体表单 -->
    <div 
      v-if="showEditForm" 
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in"
    >
      <div 
        class="p-6 rounded-xl shadow-xl max-w-xl w-full mx-4 border animate-scale-in"
        :class="isDarkMode ? 'bg-gray-900 border-gray-700' : 'bg-white border-gray-200'"
      >
        <div class="flex items-center justify-between mb-5">
          <h3 
            class="text-xl font-bold bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent animate-gradient-x"
          >
            修改自定义智能体
          </h3>
          <button 
            @click="showEditForm = false"
            class="p-2 rounded-full transition-all duration-300 transform hover:scale-110 hover:rotate-90"
            :class="isDarkMode ? 'hover:bg-gray-800 text-gray-400' : 'hover:bg-gray-100 text-gray-600'"
          >
            <font-awesome-icon icon="times" />
          </button>
        </div>
        
        <!-- 表单 -->
        <form @submit.prevent="updateCustomAgent" class="space-y-4">
          <!-- 名称 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              智能体名称
            </label>
            <input
              v-model="editingAgent.name"
              type="text"
              required
              placeholder="输入名称"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            />
          </div>
          
          <!-- 描述 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              描述
            </label>
            <textarea
              v-model="editingAgent.description"
              rows="3"
              placeholder="输入智能体描述"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border resize-none"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            ></textarea>
          </div>
          
          <!-- 预设提示语 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              预设提示语
            </label>
            <textarea
              v-model="editingAgent.systemPrompt"
              rows="5"
              placeholder="输入预设提示语，告诉AI应该扮演什么角色"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border resize-none"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            ></textarea>
          </div>
          
          <!-- 标签 -->
          <div>
            <label 
              class="block text-sm font-medium mb-1.5"
              :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'"
            >
              标签（用逗号分隔）
            </label>
            <input
              v-model="editingAgent.tagsInput"
              type="text"
              placeholder="例: 编程, 助手, 创意"
              class="w-full px-4 py-3 rounded-lg transition-all duration-300 outline-none border"
              :class="isDarkMode 
                ? 'bg-gray-800 border-gray-700 text-white placeholder-gray-500 focus:ring-2 focus:ring-[#8153ff]/30' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400 focus:ring-2 focus:ring-[#8153ff]/20'"
            />
          </div>
          
          <!-- 底部按钮 -->
          <div class="flex justify-end pt-4 border-t" :class="isDarkMode ? 'border-gray-800' : 'border-gray-200'">
            <button
              type="submit"
              class="px-4 py-2 rounded-lg text-white font-medium transition-all duration-500 btn-bounce bg-gradient-to-r from-[#8153ff] to-[#93dc24] hover:shadow-lg disabled:opacity-70 disabled:cursor-not-allowed flex items-center space-x-2"
              :disabled="isLoading"
            >
              <span v-if="isLoading" class="w-5 h-5">
                <svg class="animate-spin w-full h-full text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              </span>
              <span>{{ isLoading ? '保存中...' : '保存修改' }}</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, reactive, onMounted } from 'vue';
import { agentAPI } from '../services/api';
import { useUserStore } from '../stores/userStore';
import { toast } from '../services/toastService';

export default {
  name: 'AgentSelector',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    isDarkMode: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'select'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const isLoading = ref(false);
    
    // 显示控制
    const showSelector = computed(() => props.show);
    const showCustomForm = ref(false);
    const showEditForm = ref(false);
    
    // 智能体数据
    const selectedAgentId = ref(null);
    const searchQuery = ref('');
    const selectedCategory = ref('all');
    
    // 预设智能体列表
    const predefinedAgents = [
      {
        id: 'general',
        name: '通用助手',
        description: '一个全能的AI助手，可以回答各种问题，提供信息和建议。',
        icon: 'robot',
        color: 'bg-gradient-to-r from-blue-500 to-purple-500',
        systemPrompt: '你是一个乐于助人的AI助手。提供有用、安全、准确的信息。',
        tags: ['通用', '助手', '全能'],
        category: 'general'
      },
      {
        id: 'programmer',
        name: '编程专家',
        description: '精通多种编程语言，能够解答编程问题，提供代码示例和调试帮助。',
        icon: 'code',
        color: 'bg-gradient-to-r from-green-500 to-blue-500',
        systemPrompt: '你是一位经验丰富的编程专家，精通JavaScript、Python、Java等多种语言。你能提供清晰的代码示例，帮助解决编程问题，并给出最佳实践建议。',
        tags: ['编程', '代码', '开发'],
        category: 'work'
      },
      {
        id: 'writer',
        name: '创意作家',
        description: '帮助你进行创意写作，提供灵感，完善文章结构和内容。',
        icon: 'pen-fancy',
        color: 'bg-gradient-to-r from-yellow-500 to-red-500',
        systemPrompt: '你是一位富有创造力的作家，能够帮助用户进行各类创意写作。你可以提供写作灵感、故事构思、角色发展和情节建议。',
        tags: ['写作', '创意', '文学'],
        category: 'creative'
      },
      {
        id: 'teacher',
        name: '学习导师',
        description: '耐心的教育者，擅长解释复杂概念，帮助你学习新知识。',
        icon: 'graduation-cap',
        color: 'bg-gradient-to-r from-indigo-500 to-purple-500',
        systemPrompt: '你是一位耐心、知识渊博的教育者。你的目标是帮助学生理解复杂概念，回答他们的问题，并提供额外的学习资源。使用简单明了的语言，并在必要时提供类比来帮助理解。',
        tags: ['教育', '学习', '知识'],
        category: 'education'
      },
      {
        id: 'marketer',
        name: '营销策略师',
        description: '帮助制定营销策略，提供市场分析和创意营销方案。',
        icon: 'chart-line',
        color: 'bg-gradient-to-r from-pink-500 to-red-500',
        systemPrompt: '你是一位经验丰富的营销策略师。你可以帮助分析市场趋势，制定营销策略，提供品牌建设和内容创作的建议。',
        tags: ['营销', '策略', '商业'],
        category: 'work'
      },
      {
        id: 'travel',
        name: '旅行顾问',
        description: '提供旅行建议，景点推荐，行程规划和旅行技巧。',
        icon: 'plane',
        color: 'bg-gradient-to-r from-teal-500 to-blue-500',
        systemPrompt: '你是一位知识渊博的旅行顾问。你可以提供关于世界各地旅行目的地的信息，推荐景点，规划行程，提供预算建议和旅行技巧。',
        tags: ['旅行', '探索', '规划'],
        category: 'lifestyle'
      }
    ];
    
    // 用户自定义智能体
    const customAgents = ref([]);
    
    // 所有智能体
    const allAgents = computed(() => {
      return [...predefinedAgents, ...customAgents.value];
    });
    
    // 类别列表
    const categories = [
      { id: 'all', name: '全部', icon: 'th-large' },
      { id: 'favorites', name: '我的收藏', icon: 'star', color: 'text-yellow-400' },
      { id: 'general', name: '通用', icon: 'star' },
      { id: 'work', name: '工作', icon: 'briefcase' },
      { id: 'creative', name: '创意', icon: 'paint-brush' },
      { id: 'education', name: '教育', icon: 'book' },
      { id: 'lifestyle', name: '生活', icon: 'heart' },
      { id: 'custom', name: '自定义', icon: 'user-edit' }
    ];
    
    // 过滤后的智能体列表
    const filteredAgents = computed(() => {
      return allAgents.value.filter(agent => {
        // 确保agent.tags始终是数组
        if (!agent.tags) {
          agent.tags = ['自定义'];
        } else if (!Array.isArray(agent.tags)) {
          try {
            // 尝试将非数组的tags转换为数组
            if (typeof agent.tags === 'string') {
              agent.tags = agent.tags.split(',').map(tag => tag.trim()).filter(tag => tag);
            } else if (typeof agent.tags === 'object') {
              agent.tags = Object.values(agent.tags);
            } else {
              agent.tags = ['自定义'];
            }
          } catch (e) {
            console.error('处理智能体标签失败:', e);
            agent.tags = ['自定义'];
          }
        }
        
        // 类别过滤
        const categoryMatch = 
          selectedCategory.value === 'all' || 
          (selectedCategory.value === 'custom' && customAgents.value.some(a => a.id === agent.id)) ||
          (selectedCategory.value === 'favorites' && agent.isFavorite) ||
          agent.category === selectedCategory.value;
        
        // 搜索过滤
        if (!searchQuery.value) return categoryMatch;
        
        const query = searchQuery.value.toLowerCase();
        try {
          return categoryMatch && (
            agent.name.toLowerCase().includes(query) ||
            (agent.description && agent.description.toLowerCase().includes(query)) ||
            (Array.isArray(agent.tags) && agent.tags.some(tag => 
              tag && typeof tag === 'string' && tag.toLowerCase().includes(query)
            ))
          );
        } catch (error) {
          console.error('搜索过滤时出错:', error);
          return categoryMatch;
        }
      });
    });
    
    // 自定义智能体表单
    const customAgent = reactive({
      name: '',
      description: '',
      systemPrompt: '',
      tagsInput: '',
      icon: 'user-astronaut',
      color: 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]',
    });
    
    // 编辑智能体表单
    const editingAgent = reactive({
      id: '',
      name: '',
      description: '',
      systemPrompt: '',
      tagsInput: '',
      icon: 'user-astronaut',
      color: 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]',
    });
    
    // 加载用户自定义智能体
    const loadUserAgents = async () => {
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        console.log('用户未登录，无法加载自定义智能体');
        return;
      }
      
      try {
        isLoading.value = true;
        
        // 获取用户智能体和收藏状态
        const [agentsResponse, favoritesResponse] = await Promise.all([
          agentAPI.getUserAgents(),
          agentAPI.getFavorites()
        ]);
        
        // 处理自定义智能体
        if (agentsResponse && agentsResponse.data) {
          console.log('从后端收到智能体数据:', agentsResponse.data);
          
          customAgents.value = agentsResponse.data.map(agent => {
            // 确保tags是数组
            let tags = agent.tags;
            if (!tags) {
              tags = ['自定义'];
            } else if (!Array.isArray(tags)) {
              try {
                if (typeof tags === 'string') {
                  // 尝试解析JSON字符串
                  try {
                    const parsed = JSON.parse(tags);
                    tags = Array.isArray(parsed) ? parsed : [tags];
                  } catch {
                    // 如果不是JSON，视为逗号分隔的字符串
                    tags = tags.split(',').map(t => t.trim()).filter(t => t);
                  }
                } else if (typeof tags === 'object') {
                  tags = Object.values(tags);
                } else {
                  tags = ['自定义'];
                }
              } catch (e) {
                console.error(`处理智能体(${agent.id})的标签出错:`, e);
                tags = ['自定义'];
              }
            }
            
            // 处理系统提示词字段，兼容不同的命名约定
            const systemPrompt = agent.systemPrompt || agent.system_prompt || '';
            
            console.log(`处理智能体(${agent.id})的系统提示词:`, {
              rawSystemPrompt: agent.systemPrompt,
              rawSystem_prompt: agent.system_prompt,
              processedValue: systemPrompt
            });
            
            // 添加isCustom标志并返回处理后的agent对象
            return {
              ...agent,
              tags,
              systemPrompt,
              isCustom: true
            };
          });
          console.log('成功加载用户自定义智能体', customAgents.value);
        }
        
        // 处理收藏状态
        if (favoritesResponse && favoritesResponse.data) {
          const favoriteIds = favoritesResponse.data;
          console.log('成功加载收藏智能体ID列表', favoriteIds);
          
          // 更新预设智能体的收藏状态
          predefinedAgents.forEach(agent => {
            agent.isFavorite = favoriteIds.includes(agent.id);
          });
          
          // 更新自定义智能体的收藏状态（如果API没有直接返回）
          customAgents.value.forEach(agent => {
            if (!agent.hasOwnProperty('isFavorite')) {
              agent.isFavorite = favoriteIds.includes(agent.id);
            }
          });
        }
      } catch (error) {
        console.error('加载用户数据失败:', error);
        const errorMsg = error.message || '加载数据失败';
        toast.error(errorMsg, 3000);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 方法
    function closeSelector() {
      emit('close');
    }
    
    function selectCategory(categoryId) {
      selectedCategory.value = categoryId;
    }
    
    function selectAgent(agent) {
      selectedAgentId.value = agent.id;
    }
    
    function openCustomAgentForm() {
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再创建自定义智能体', 3000);
        return;
      }
      
      showCustomForm.value = true;
    }
    
    async function saveCustomAgent() {
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再创建自定义智能体', 3000);
        return;
      }
      
      try {
        isLoading.value = true;
        
        const tags = customAgent.tagsInput.split(',')
          .map(tag => tag.trim())
          .filter(tag => tag !== '');
        
        const newAgent = {
          id: `custom-${Date.now()}`,
          name: customAgent.name,
          description: customAgent.description,
          systemPrompt: customAgent.systemPrompt,
          icon: customAgent.icon,
          color: customAgent.color,
          tags: tags.length > 0 ? tags : ['自定义'],
          category: 'custom',
          isCustom: true
        };
        
        // 保存到数据库
        const response = await agentAPI.createAgent(newAgent);
        
        if (response && response.data) {
          // 使用返回的数据，确保id和其他属性正确
          customAgents.value.push(response.data);
          
          toast.success('自定义智能体创建成功', 2000);
          showCustomForm.value = false;
          
          // 重置表单
          customAgent.name = '';
          customAgent.description = '';
          customAgent.systemPrompt = '';
          customAgent.tagsInput = '';
          
          // 自动选择新创建的智能体
          selectedAgentId.value = response.data.id;
          selectedCategory.value = 'custom';
        }
      } catch (error) {
        console.error('保存自定义智能体失败:', error);
        const errorMsg = error.message || '创建自定义智能体失败';
        toast.error(errorMsg, 3000);
      } finally {
        isLoading.value = false;
      }
    }
    
    async function deleteCustomAgent(agentId) {
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再删除智能体', 3000);
        return;
      }
      
      try {
        if (confirm('确定要删除这个智能体吗？此操作不可恢复。')) {
          isLoading.value = true;
          
          await agentAPI.deleteAgent(agentId);
          
          // 从列表中移除
          customAgents.value = customAgents.value.filter(a => a.id !== agentId);
          
          // 如果当前选择的是被删除的智能体，清除选择
          if (selectedAgentId.value === agentId) {
            selectedAgentId.value = null;
          }
          
          toast.success('智能体已成功删除', 2000);
        }
      } catch (error) {
        console.error('删除智能体失败:', error);
        const errorMsg = error.message || '删除智能体失败';
        toast.error(errorMsg, 3000);
      } finally {
        isLoading.value = false;
      }
    }
    
    function editCustomAgent(agent) {
      // 检查用户是否已登录
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再修改智能体', 3000);
        return;
      }
      
      try {
        console.log('准备编辑的智能体:', agent);
        
        // 设置要编辑的智能体信息
        editingAgent.id = agent.id;
        editingAgent.name = agent.name || '';
        editingAgent.description = agent.description || '';
        
        // 处理systemPrompt字段，优先使用agent.systemPrompt，如果不存在则尝试使用agent.system_prompt
        // 这样可以处理不同命名约定的数据
        editingAgent.systemPrompt = agent.systemPrompt || agent.system_prompt || '';
        
        // 在控制台输出，帮助调试
        console.log('设置编辑表单的预设提示语:', {
          rawSystemPrompt: agent.systemPrompt, 
          rawSystem_prompt: agent.system_prompt,
          processedValue: editingAgent.systemPrompt
        });
        
        editingAgent.icon = agent.icon || 'user-astronaut';
        editingAgent.color = agent.color || 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]';
        
        // 安全处理tags字段
        let tagsStr = '';
        if (agent.tags) {
          if (Array.isArray(agent.tags)) {
            // 如果是数组，使用join转换为字符串
            tagsStr = agent.tags.join(', ');
          } else if (typeof agent.tags === 'string') {
            // 如果已经是字符串，直接使用
            tagsStr = agent.tags;
          } else if (typeof agent.tags === 'object') {
            // 如果是对象（如JSON对象），尝试转换为数组再join
            try {
              const tagsArray = Object.values(agent.tags);
              tagsStr = tagsArray.join(', ');
            } catch (e) {
              console.error('Tags对象转换失败:', e);
              tagsStr = '自定义';
            }
          }
        }
        editingAgent.tagsInput = tagsStr;
        
        // 显示编辑表单
        showEditForm.value = true;
      } catch (error) {
        console.error('准备编辑智能体时出错:', error);
        toast.error('编辑智能体失败，请稍后再试', 3000);
      }
    }
    
    async function updateCustomAgent() {
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再修改智能体', 3000);
        return;
      }
      
      try {
        isLoading.value = true;
        
        // 基本验证
        if (!editingAgent.name || !editingAgent.systemPrompt) {
          toast.error('名称和预设提示语不能为空', 3000);
          isLoading.value = false;
          return;
        }
        
        // 安全处理tags字段
        let tags = [];
        try {
          if (editingAgent.tagsInput) {
            tags = editingAgent.tagsInput.split(',')
              .map(tag => tag.trim())
              .filter(tag => tag !== '');
          }
        } catch (error) {
          console.error('处理标签时出错:', error);
          // 出错时使用默认标签，而不是中断整个操作
          tags = ['自定义'];
        }
        
        const updatedAgent = {
          id: editingAgent.id,
          name: editingAgent.name,
          description: editingAgent.description || '',
          systemPrompt: editingAgent.systemPrompt,
          system_prompt: editingAgent.systemPrompt, // 同时包含两种形式，确保后端能正确处理
          icon: editingAgent.icon || 'user-astronaut',
          color: editingAgent.color || 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]',
          tags: tags.length > 0 ? tags : ['自定义'],
          category: 'custom'
        };
        
        console.log('准备更新智能体:', updatedAgent);
        
        // 保存到数据库
        const response = await agentAPI.updateAgent(editingAgent.id, updatedAgent);
        
        if (response && response.data) {
          console.log('更新智能体成功，服务器响应:', response.data);
          
          // 更新本地智能体列表
          const index = customAgents.value.findIndex(a => a.id === editingAgent.id);
          if (index !== -1) {
            // 确保保留isFavorite属性
            const isFavorite = customAgents.value[index].isFavorite;
            
            // 处理返回数据，确保systemPrompt字段正确
            const returnedAgent = {
              ...response.data,
              systemPrompt: response.data.systemPrompt || response.data.system_prompt,
              isCustom: true,
              isFavorite
            };
            
            // 更新智能体信息
            customAgents.value[index] = returnedAgent;
          }
          
          toast.success('自定义智能体修改成功', 2000);
          showEditForm.value = false;
        } else {
          throw new Error('服务器未返回有效数据');
        }
      } catch (error) {
        console.error('更新自定义智能体失败:', error);
        const errorMsg = error.message || '修改自定义智能体失败';
        toast.error(errorMsg, 3000);
      } finally {
        isLoading.value = false;
      }
    }
    
    function confirmSelection() {
      if (!selectedAgentId.value) return;
      
      const selectedAgent = allAgents.value.find(agent => agent.id === selectedAgentId.value);
      if (selectedAgent) {
        emit('select', selectedAgent);
        closeSelector();
      }
    }
    
    async function toggleFavorite(agent) {
      if (!userStore.isLoggedIn) {
        toast.error('请先登录后再收藏智能体', 3000);
        return;
      }
      
      // 保存原始状态，以便在API调用失败时恢复
      const originalState = agent.isFavorite;
      
      // 强制直接修改DOM元素的样式，确保立即生效
      const button = event.currentTarget;
      
      try {
        // 立即在UI上更新状态
        agent.isFavorite = !agent.isFavorite;
        
        // 立即更新按钮样式
        button.style.backgroundColor = agent.isFavorite ? '#facc15' : '#6b7280';
        
        // 显示弹窗提示
        if (agent.isFavorite) {
          toast.success(`收藏成功！"${agent.name}"已添加到您的收藏列表`, 3000, {
            icon: '⭐',
            style: {
              background: 'linear-gradient(to right, #fbbf24, #ea580c)',
              color: 'white',
              fontSize: '1.1rem',
              fontWeight: 'bold',
              padding: '15px 20px',
              borderRadius: '10px',
              boxShadow: '0 8px 16px rgba(251, 191, 36, 0.6)',
              border: '2px solid #fef3c7',
              textAlign: 'center',
              width: '320px'
            },
            position: 'center'
          });
          
          // 显示一个关于如何查看收藏的提示
          setTimeout(() => {
            toast.info('点击"我的收藏"标签可查看所有收藏的智能体', 3000, {
              icon: '👆',
              style: {
                background: 'linear-gradient(to right, #3b82f6, #1d4ed8)',
                color: 'white',
                fontSize: '1rem',
                padding: '12px 16px',
                borderRadius: '8px',
                boxShadow: '0 4px 12px rgba(59, 130, 246, 0.5)',
                textAlign: 'center',
                width: '300px'
              },
              position: 'bottom-center'
            });
          }, 1500);
        } else {
          toast.info(`已取消收藏！"${agent.name}"已从您的收藏列表中移除`, 3000, {
            icon: '✓',
            style: {
              background: 'linear-gradient(to right, #475569, #64748b)',
              color: 'white',
              fontSize: '1.1rem',
              fontWeight: 'bold',
              padding: '15px 20px',
              borderRadius: '10px',
              boxShadow: '0 8px 16px rgba(100, 116, 139, 0.6)',
              border: '2px solid #e2e8f0',
              textAlign: 'center',
              width: '320px'
            },
            position: 'center'
          });
        }
        
        // 调用API，确保服务器端持久化存储
        const response = await agentAPI.toggleFavorite({
          agentId: agent.id,
          isFavorite: agent.isFavorite
        });
        
        if (!response || !response.data || response.data.error) {
          // API返回错误，回滚状态并显示错误
          throw new Error(response?.data?.message || '保存失败');
        }
        
        // 服务器确认已成功保存
        console.log('收藏状态已成功保存:', agent.id, agent.isFavorite);
        
        // 确保和服务器状态同步
        if (response.data.isFavorite !== undefined) {
          agent.isFavorite = response.data.isFavorite;
          button.style.backgroundColor = agent.isFavorite ? '#facc15' : '#6b7280';
        }
        
      } catch (error) {
        // 出错，回滚UI状态
        agent.isFavorite = originalState;
        
        // 回滚按钮样式
        button.style.backgroundColor = originalState ? '#facc15' : '#6b7280';
        
        console.error('切换收藏状态失败:', error);
        
        // 显示明显的错误弹窗
        toast.error('收藏操作失败！服务器未能保存您的更改，请稍后重试', 3000, {
          style: {
            background: 'linear-gradient(to right, #ef4444, #b91c1c)',
            color: 'white',
            fontSize: '1.1rem',
            fontWeight: 'bold',
            padding: '15px 20px',
            borderRadius: '10px',
            boxShadow: '0 8px 16px rgba(239, 68, 68, 0.6)',
            border: '2px solid #fee2e2',
            textAlign: 'center',
            width: '350px'
          },
          position: 'center'
        });
      }
    }
    
    // 在组件挂载时加载用户自定义智能体
    onMounted(() => {
      loadUserAgents();
    });
    
    return {
      isDarkMode: computed(() => props.isDarkMode),
      showSelector,
      showCustomForm,
      showEditForm,
      selectedAgentId,
      searchQuery,
      selectedCategory,
      categories,
      filteredAgents,
      customAgent,
      editingAgent,
      isLoading,
      closeSelector,
      selectCategory,
      selectAgent,
      openCustomAgentForm,
      saveCustomAgent,
      deleteCustomAgent,
      editCustomAgent,
      updateCustomAgent,
      confirmSelection,
      toggleFavorite
    };
  }
};
</script>

<style scoped>
.btn-bounce:active {
  transform: scale(0.95);
}

.stagger-item {
  animation: staggerFadeIn 0.5s ease forwards;
  opacity: 0;
  animation-delay: var(--stagger-delay, 0ms);
}

/* 按钮位置样式 */
.right-11 {
  right: 2.75rem !important; /* 编辑按钮位置 */
}

.right-20 {
  right: 5rem !important; /* 删除按钮位置 */
}

.right-29 {
  right: 7.25rem !important; /* 选中指示器位置 */
}

@keyframes staggerFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-scale-in {
  animation: scaleIn 0.3s ease-out forwards;
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.animate-gradient-x {
  background-size: 200% 200%;
  animation: gradientPosition 3s ease infinite;
}

@keyframes gradientPosition {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.animate-pulse-slow {
  animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 0.3;
  }
}
</style> 